from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from .models import User
from django import forms


class UserCreationForm(forms.ModelForm):
    """用于后台创建用户的表单"""
    password1 = forms.CharField(label="密码", widget=forms.PasswordInput)
    password2 = forms.CharField(label="确认密码", widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'email', 'phone')

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("两次输入的密码不一致")
        return password2

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """用于后台修改用户的表单"""

    class Meta:
        model = User
        fields = '__all__'  # 包括所有字段


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm
    model = User

    list_display = ('username', 'email', 'phone', 'nickname', 'is_staff', 'is_active')
    list_filter = ('is_active', 'is_staff', 'is_superuser', 'date_joined')
    search_fields = ('username', 'email', 'phone', 'nickname')
    ordering = ('-date_joined',)

    readonly_fields = ('date_joined', 'last_login', 'last_updated')

    fieldsets = (
        (_("登录信息"), {"fields": ("username", "password")}),
        (_("个人信息"), {"fields": ("nickname", "email", "phone", "avatar", "biography")}),
        (_("权限"), {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions")}),
        (_("时间信息"), {"fields": ("last_login", "date_joined", "last_updated")}),
    )

    add_fieldsets = (
        (None, {
            "classes": ("wide",),
            "fields": ("username", "email", "phone", "password1", "password2", "is_active", "is_staff"),
        }),
    )
